package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.User;
import com.example.entity.UserRole;
import com.example.service.IUserRoleService;
import com.example.service.IUserService;
import com.example.service.RedisService;
import com.example.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author daiweiyuan
 */
@Slf4j
@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 根据用户id清除用户权限缓存和登录信息缓存
     *
     * @param userId 用户id
     */
    @Override
    public void clearUserAuthoritiesInfo(Integer userId) {
        String userName = userService.getUserNameById(userId);
        this.redisUtil.del("userDetails:" + userName);
        this.redisUtil.del("GrantedAuthority:" + userName);
    }

    /**
     * 根据菜单id清除用户权限缓存
     *
     * @param menuId
     */
    @Override
    public void clearUserAuthorityInfoByMenuId(Integer menuId) {
        List<User> sysUsers = userService.listByMenuId(menuId);
        sysUsers.forEach(u -> {
            this.clearUserAuthoritiesInfo(u.getId());
        });
    }

    /**
     * 根据角色id清除用户权限缓存
     *
     * @param roleId
     */
    @Override
    public void clearUserAuthorityInfoByRoleId(Integer roleId) {
        List<UserRole> userRoles = userRoleService.list(new QueryWrapper<UserRole>().eq("role_id", roleId));
        userRoles.forEach(ur -> {
            this.clearUserAuthoritiesInfo(ur.getUserId());
        });
    }
}
